<?php

class OrderController extends Controller
{
	/**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   /**
	 * action array filter
	 */
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
   public function actionIndex()
	{
		$page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $sidx = isset($_GET['sidx']) ?  $_GET['sidx'] : 'ord_id'; // Lấy trường cần sắp xếp
      $sord = isset($_GET['sord']) ? $_GET['sord'] : 'DESC'; // Lấy giá trị muốn sắp xếp
      $start = $limit*$page - $limit; // Thứ tự bản ghi bắt đầu lấy
      $rowList = array(10,20,30,50,100);  
      //Biến xác định phiên làm việc của user
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;  
      $list = array();
      $model = new Orders();
      $model->unsetAttributes();
      
      $criteria = new CDbCriteria;
      $criteria->limit = $limit;
      $criteria->offset = $start;
      $criteria->order = $sidx . ' ' . $sord;
      if(isset($_POST['Orders'])){ // Nếu người dùng search
         $model->attributes = $_POST['Orders'];
         $params = array();
         
         if(isset($_POST['start_date'])){
            $criteria->addCondition("ord_date >= :start_date", "AND");
            $params[':start_date'] = strtotime(str_replace('/','-',$_POST['start_date']));
         }
         if(isset($_POST['end_date'])){
            $criteria->addCondition("ord_date <= :end_date", "AND");
            $params[':end_date'] = strtotime(str_replace('/','-',$_POST['end_date'])) + 86400; //Cuối ngày
         }
         if($model->ord_status != 2){
            $criteria->addCondition("ord_status = :ord_status", "AND");
            $params[':ord_status'] = $model->ord_status;
         }
         $criteria->params = $params;
      }
      
      $object = $model->with('products')->findAll($criteria);
      
      if(count($object) > 0){
         
         foreach($object as $item){
            $list[$item->attributes['ord_id']] = $item->attributes;
            $related_products = $item->getRelated('products');
            $products = array();
            if(count($related_products) > 0){
               foreach($related_products as $related_item){
                  $products[] = $related_item->attributes;
               }
            }
            $list[$item->attributes['ord_id']]['products'] = $products;   
         }
      }
      $total_record = $model->count($criteria); // Đếm tổng số bản ghi
      if( $total_record >0 ) {
      	$total_pages = ceil($total_record/$limit);
      } else {
      	$total_pages = 0;
      }
      
      //CVarDumper::dump($list,10,true);die();
      $this->render('index',array('model' => $model,
                                  'session_user' => $session_user,
                                  'list' => $list,
                                  'rowList' => $rowList,
                                  'page' => $page,
                                  'start' => $start,
                                  'limit' => $limit,
                                  'total_record' => $total_record,
                                  'total_pages' => $total_pages,
                                  ));
	}
   
   /**
    * Deactive record
   */
	public function actionDeactive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE orders SET ord_status = 0 WHERE ord_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Active record
   */
	public function actionActive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE orders SET ord_status = 1 WHERE ord_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Delete record
   */
	public function actionDelete(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'DELETE FROM orders WHERE ord_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}